package com.talent.jiwen.teacher;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseFragment;
import com.talent.jiwen.chatlive.InteractiveActivity;
import com.talent.jiwen.home.AddProblemActivity;
import com.talent.jiwen.home.AddProblemNewActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.GroupInfoResult;
import com.talent.jiwen.http.result.OrderAllResult;
import com.talent.jiwen.http.result.OrderResult;
import com.talent.jiwen.my.EvaluateActivity;
import com.talent.jiwen.my.PayActivity;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.DateUtils;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Observable;

public class CourseAllListFragment extends BaseFragment {
    @BindView(R.id.recycleView)
    RecyclerView recycleView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noDataIv)
    ImageView noDataIv;

    private int startIndex = 1;

    private List<OrderAllResult.OrderAll> dataList = new ArrayList<>();

    public static final String REFRESH_COURSE_ALL_LIST = "refresh.course.all.list";

    @Override
    protected void initData() {

        registEventBus();

        noDataIv.setImageResource(R.mipmap.img_no_order);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recycleView.setLayoutManager(linearLayoutManager);

        recycleView.setAdapter(new CommonAdapter<OrderAllResult.OrderAll>(getActivity() , R.layout.item_course_all_list , dataList){
            @Override
            protected void convert(ViewHolder holder, final OrderAllResult.OrderAll data, int position) {
                ImageView headIv = holder.getView(R.id.headIv);
                TextView nameTv = holder.getView(R.id.nameTv);
                TextView statusTv = holder.getView(R.id.statusTv);
                TextView typeTv = holder.getView(R.id.typeTv);
                TextView studyTimeTv = holder.getView(R.id.studyTimeTv);
                TextView useTimeTv = holder.getView(R.id.useTimeTv);
                TextView orderNumberTv = holder.getView(R.id.orderNumberTv);
                TextView moneyTv = holder.getView(R.id.moneyTv);
                TextView waitPayTv = holder.getView(R.id.waitPayTv);
                TextView oneMoreTv = holder.getView(R.id.oneMoreTv);
                TextView commentTv = holder.getView(R.id.commentTv);
                LinearLayout optionLayout = holder.getView(R.id.optionLayout);

                ImageUtil.loadCorner4Image(getActivity() , data.getTeacherHeadImage() , headIv);

                headIv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (data.getTeacherId() != 0){
                            TeacherDetailActivity.startTeacherDetailActivity(getActivity() , TeacherDetailActivity.TYPE_ASK_PROBLEM , data.getTeacherId()+"" , "");
                        }else{
                            showToast("该单已取消，无法查看老师详情");
                        }
                    }
                });

                String subjectName = Constant.subjectMap.get(data.getSubjectId());
                String grade = "";
                if (data.getGradeLevel() >= 1 && data.getGradeLevel() <= 6 ){
                    grade = "小学";
                }else if (data.getGradeLevel() > 6  && data.getGradeLevel() < 10){
                    grade = "初中";
                }else{
                    grade = "高中";
                }
                nameTv.setText(grade + subjectName + data.getTeacherName());

                if(data.getMemberCount() > 1){
                    typeTv.setVisibility(View.VISIBLE);
                    typeTv.setText("拼班");
                }else{
                    typeTv.setVisibility(View.GONE);
                }


                studyTimeTv.setText("时间：" + DateUtils.ms2Date(data.getCreateTime()));
                orderNumberTv.setText(data.getOrderNo());

                moneyTv.setText("¥"+ data.getPersonalPrice());

                useTimeTv.setText("用时："+ DateUtils.getDatePoor(data.getEndTime() - data.getStartTime()));

                //评论
                commentTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        EvaluateActivity.startEvaluateActivity(getActivity() , data.getId() , data.getTeacherId() + "");
                    }
                });

                //付款
                waitPayTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PayActivity.startPayActivity(getActivity() , data.getId());
                    }
                });

                //重新提问
                oneMoreTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        askOneMore(data.getQuestionIntroduction() , data.getQuestionImages() , data.getSubjectId());
                    }
                });

                switch (data.getOrderStatus()){
                    case 2:
                        //已取消
                        optionLayout.setVisibility(View.VISIBLE);
                        oneMoreTv.setVisibility(View.VISIBLE);
                        commentTv.setVisibility(View.GONE);
                        waitPayTv.setVisibility(View.GONE);

                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.red));
                        statusTv.setText("已取消");
                        break;
                    case 3:
                        //退款中
                        optionLayout.setVisibility(View.GONE);
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.red));
                        statusTv.setText("退款中");
                        break;
                    case 4:
                        //已退款
                        optionLayout.setVisibility(View.GONE);
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.red));
                        statusTv.setText("已退款");
                        break;
                    case 6:
                        //已结束（未支付）
                        useTimeTv.setVisibility(View.VISIBLE);

                        optionLayout.setVisibility(View.VISIBLE);
                        commentTv.setVisibility(View.GONE);
                        waitPayTv.setVisibility(View.VISIBLE);
                        oneMoreTv.setVisibility(View.GONE);

                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.text_gray_3));
                        statusTv.setText("等待支付");
                        break;
                    case 7:
                        //已支付
                        useTimeTv.setVisibility(View.VISIBLE);
                        if (data.getEvaluateStatus() == 0){
                            //未评论
                            optionLayout.setVisibility(View.VISIBLE);
                            commentTv.setVisibility(View.VISIBLE);
                            oneMoreTv.setVisibility(View.GONE);
                            waitPayTv.setVisibility(View.GONE);
                        }else{
                            //已评论
                            optionLayout.setVisibility(View.GONE);
                        }
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.text_gray_3));
                        statusTv.setText("订单已完成");
                        break;
                    case 8:
                        //异常单（学生未进入）
                        optionLayout.setVisibility(View.GONE);
                        useTimeTv.setVisibility(View.GONE);
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.red));
                        statusTv.setText("异常单(学生未进入)");
                        break;
                    case 10:
                        //异常单（教师未进入）
                        optionLayout.setVisibility(View.GONE);
                        useTimeTv.setVisibility(View.GONE);
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.red));
                        statusTv.setText("异常单(教师未进入)");
                        break;
                    case 12:
                        //已结算，已支付，不能退款
                        useTimeTv.setVisibility(View.VISIBLE);
                        if (data.getEvaluateStatus() == 0){
                            //未评论
                            optionLayout.setVisibility(View.VISIBLE);
                            commentTv.setVisibility(View.VISIBLE);
                            oneMoreTv.setVisibility(View.GONE);
                            waitPayTv.setVisibility(View.GONE);

                        }else{
                            //已评论
                            optionLayout.setVisibility(View.GONE);
                        }
                        statusTv.setTextColor(ContextCompat.getColor(getActivity() , R.color.text_gray_3));
                        statusTv.setText("订单已完成");
                        break;
                    default:
                        optionLayout.setVisibility(View.GONE);
                        break;
                }



                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        switch (data.getOrderStatus()){
                            case 6:
                                PayActivity.startPayActivity(getActivity() , data.getId());
                                break;
                            default:
                                OrderDetailActivity.startOrderDetailActivity(getActivity(), data.getId());
                                break;
                        }
                    }
                });
            }
        });


        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                startIndex = 1;
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                startIndex ++;
                getOrderList();
            }
        });

        refreshLayout.autoRefresh();
    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_COURSE_ALL_LIST)){
            refreshLayout.autoRefresh();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_course_list;
    }

    /**获取订单列表
     *
     */
    private void getOrderList(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.getUserId());
        map.put("startIndex" , startIndex + "");

        Observable observable = ApiFactory.getEducationApiSingleton().getCompletedOrderList(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderAllResult>(getActivity()) {
            @Override
            protected void _onNext(OrderAllResult orderAllResult) {
                if(startIndex == 1){
                    dataList.clear();
                    dataList.addAll(orderAllResult.getOrderList());
                    recycleView.getAdapter().notifyDataSetChanged();
                    refreshLayout.finishRefresh();
                }else{
                    dataList.addAll(orderAllResult.getOrderList());
                    recycleView.getAdapter().notifyDataSetChanged();
                    refreshLayout.finishLoadMore();

                    if (orderAllResult.getOrderList().size() < 10){
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }

                if (Validators.isEmpty(dataList)){
                    noDataIv.setVisibility(View.VISIBLE);
                }else{
                    noDataIv.setVisibility(View.GONE);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                if (null != refreshLayout){
                    refreshLayout.finishRefresh();
                }
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**重新提问
     *
     */
    private void askOneMore(final String content , final String questionImgs , final int subjectId){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().createGroupInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<GroupInfoResult>(getActivity()) {
            @Override
            protected void _onNext(GroupInfoResult groupInfoResult) {

                String groupId = groupInfoResult.getGroupId();
                int couponCount = groupInfoResult.getAvailableCouponCount();
                boolean hasOrderNow = false;
                if (groupInfoResult.getExistImmediateStatus() == 0){
                    hasOrderNow = false;
                }else{
                    hasOrderNow = true;
                }

                AddProblemActivity.startAddProblemActivity(getActivity() , groupId , couponCount , hasOrderNow
                        , "","" , content  , questionImgs , subjectId);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }
}
